'use strict'

const rp = require('request-promise')

const config = {

  uri: 'https://birdie2.wilddogio.com/tournaments/'

}

module.exports = function (options) {
  return new RtUtils(options)
}

function RtUtils (options) {

  this.uri = config.uri + `${options.tournamentObjId}/subTournaments/${options.subTournamentObjId}`
  this.stage = options.stage
  this.queueKey = options.queueKey

}

RtUtils.prototype.saveState = function () {

  const uri = this.uri + `/queue/${this.queueKey}/state.json`

  return rp({
    method: 'PUT',
    uri,
    body: 'completed'
  })

}

RtUtils.prototype.saveGroupMatch = function () {

  const uri = this.uri + `/groups/${this.stage.groupIndex}/matches/${this.stage.matchIndex}/state.json`
  const queueStateUri = this.uri + `/queue/${queueKey}/state.json`
  const wUri = this.uri + `/groups/${this.stage.groupIndex}/teams/${this.stage.teamIndex[winnerIndex]}/scores/w.json`
  const lUri = this.uri + `/groups/${this.stage.groupIndex}/teams/${this.stage.teamIndex[loserIndex]}/scores/l.json`
  const groupWUri = this.uri + `/groups/${this.stage.groupIndex}/winners.json`
  const groupLUri = this.uri + `/groups/${this.stage.groupIndex}/losers.json`

  return this.saveState()
  .then(() => {
    return rp({
      method: 'PUT',
      uri,
      body: 'completed'
    })
  }).then(() => {
    var promises = [
      rp({
        uri: wUri,
        method: 'POST',
        body: ' '
      }),
      rp({
        uri: lUri,
        method: 'POST',
        body: ' '
      })
    ]
    return Promise.all(promises)
  }).then(() => {
    var promises = [
      rp({
        uri: groupWUri,
        method: 'POST',
        body: this.stage.teamIndex[winnerIndex] + ''
      }),
      rp({
        uri: groupLUri,
        method: 'POST',
        body: this.stage.teamIndex[loserIndex] + ''
      })
    ]
    return Promise.all(promises)
  })

}

RtUtils.prototype.savePlayoffsMatch = function () {
  return this.saveState()
  .then(() => {
    const uri = this.uri + `/playoffs/${this.stage.roundIndex}/matches/${this.stage.matchIndex}/state.json`
    return rp({
      method: 'PUT',
      uri,
      body: 'complete'
    }).then(() => {
      // todo
      const uri = this.uri + `/playoffs/${this.stage.roundIndex}/matches/${this.stage.matchIndex}/state.json`
    })
  })
}

RtUtils.prototype.queueUp = function () {
  
}
